//
//  MasterViewController.m
//  Iderun
//
//  Created by Zhou, Shaolin on 6/10/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "photolistViewController.h"
#import "XmlReader.h"
#import "photolistCell.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "JSON.h"
#import "UIImageUIImageExt.h"
#import "PhotoDetailViewController.h"
#import "CustomNavigationController.h"


@implementation photolistViewController

@synthesize _tableView,resultData;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        if ([self respondsToSelector:@selector(edgesForExtendedLayout)]) {
            self.edgesForExtendedLayout = UIRectEdgeNone;
        }

        self.title = @"拍照上传列表";
      
    }
    return self;
}



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.resultData=[NSMutableArray array];
    CGRect rect=[[UIScreen mainScreen] bounds];
    rect.size.height=rect.size.height-[UIApplication sharedApplication].statusBarFrame.size.height-self.navigationController.navigationBar.frame.size.height-self.tabBarController.tabBar.frame.size.height;
    rect.origin.y=0;
    UITableView *tableView=[[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    self._tableView=tableView;
    self._tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
    self._tableView.separatorColor=[UIColor colorWithRed:228.0/255 green:250.0/255 blue:254.0/255 alpha:1.0];
    [_tableView  release];
    [self.view  addSubview:self._tableView];
    self._tableView.delegate=self;
    self._tableView.dataSource=self;
    if (requestManager == nil) {
        requestManager = [[UrlRequest alloc] initWithDelegate:self requestSelector:@selector(parseReceivedData:) errorSelector:@selector(errorCallback)];
    }
    
    UIBarButtonItem *leftButton=[[UIBarButtonItem alloc] initWithCustomView:[self customButtom:100 withFrame:CGRectMake(10, 0, 33, 29) action:@selector(takephotoAction:) normalImage:@"camera_pressed.png" lightedImage:@"camera_pressed.png" title:@""]];
    leftButton.style = UIBarButtonItemStylePlain;
    self.navigationItem.leftBarButtonItem=leftButton;
    [leftButton release];
    
    
    
    UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
    customButton.frame=CGRectMake(10, 0, 21, 44);
	[customButton addTarget:self action:@selector(reflush:) forControlEvents:UIControlEventTouchUpInside];
	[customButton setImage:[UIImage imageNamed:@"head_btn_update_off.png"] forState:UIControlStateNormal];
	[customButton setBackgroundImage:[UIImage imageNamed:@"head_btn_update_on.png"] forState:UIControlStateSelected];
    [customButton setBackgroundImage:[UIImage imageNamed:@"head_btn_update_on.png"] forState:UIControlStateHighlighted];
	UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithCustomView:customButton];
    addButton.style = UIBarButtonItemStylePlain;
    self.navigationItem.rightBarButtonItem=addButton;
    [addButton release];  
    
    //******************gps********************
    if (nil==self.locmanager) {
        CLLocationManager *locmanager_=[[CLLocationManager alloc] init];
        self.locmanager= locmanager_;
        [locmanager_  release];
    }
    //**********************************
     [self  loadData];
    
}
-(void) hiddenNavBar:(BOOL) status{
    [self.navigationController setNavigationBarHidden:status animated:YES];
    if (!status) {
        _tableView.contentInset=UIEdgeInsetsMake(44.0f, 0.0f, 0.0f, 0.0f);
    }
}


-(IBAction)takephotoAction:(id)sender{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        if (nil==self.pickerController) {
            UIImagePickerController *pickerController_ = [[UIImagePickerController alloc] init];
            self.pickerController=pickerController_;
            [_pickerController release];
        }
         self.uploadType=UPLOADIMAGE;
        self.pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.pickerController.delegate=self;
        [self presentModalViewController:self.pickerController animated:YES];
    }
   
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    //圖片處理
    UIImage *rawImage=[info  objectForKey:UIImagePickerControllerOriginalImage];
   
    rawImage=[rawImage imageByScalingAndCroppingForSize:CGSizeMake(600, 800)];
    NSData *imgData = UIImageJPEGRepresentation(rawImage,0.4);
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [MBProgressHUD  showHUDAddedTo:appdelegate.tabbar.view animated:NO];
     
   
    NSDate *date=[NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:date];
    
    long time=(long)([date timeIntervalSince1970]);
   NSString *imagePath=[NSString stringWithFormat:@"\\mobileimage\\%ld.jpg",time];
     NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    [userdefault setObject:currentDateStr forKey:@"createDate"];
    [userdefault setObject:imagePath forKey:@"imagePath"];
    [userdefault setObject:[NSString stringWithFormat:@"%ld",time] forKey:@"file_id"];
    [userdefault synchronize];
    [dateFormatter release];
    [requestManager postFileWithRequest:imgData imagePath:imagePath];
    [self dismissModalViewControllerAnimated:YES];
    
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self.pickerController dismissModalViewControllerAnimated:NO];
    //NSLog(@"拍照取消。。。。");
}


-(void) viewWillAppear:(BOOL)animated{
    [super  viewWillAppear:animated];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"USER_ID"]==nil) {
        AppDelegate *appDelegate=[UIApplication sharedApplication].delegate;
        [appDelegate popLoginViewController];
        
    }
    self.locmanager.delegate=self;
    [self.locmanager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    self.locmanager.distanceFilter = 500.0f;
    [ self.locmanager startUpdatingLocation];
    
}

-(void) viewDidAppear:(BOOL)animated{
    [super  viewDidAppear: animated];
}
-(IBAction)reflush:(id)sender{
     [self  loadData];
}



-(void) loadData{
    self.uploadType=AUDITLIST;
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [MBProgressHUD  showHUDAddedTo:appdelegate.tabbar.view animated:NO];
    [requestManager tfFileList];
}

-(void)parseReceivedData:(id)data{
    //NSLog(@"%d",self.uploadType);
    if (self.uploadType==2) {
        [self loadData];
        UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"提示" message:@"上传成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alertView show];
        [alertView release];
    }
    
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [ MBProgressHUD  hideHUDForView:appdelegate.tabbar.view animated:NO];

    @try {
        if (data==nil||[data isEqualToString:@""]) {
            NSLog(@"master receivedString=%@",@"空");
            
            return;
        }
        NSError **error;
        NSDictionary *result=[XmlReader dictionaryForXMLString:data error:error];
        int temp=UPLOADIMAGE;
        if (self.uploadType==temp) {
            id  resultDict= [[[[[result  objectForKey:@"soap:Envelope"] objectForKey:@"soap:Body"] objectForKey:@"UploadFileResponse"] objectForKey:@"UploadFileResult"] objectForKey:@"text"];
            if ([resultDict boolValue]) {
                self.uploadType=INSERTIMAGEDATA;
                [ MBProgressHUD  showHUDAddedTo:appdelegate.tabbar.view animated:NO];
                [requestManager saveImageData];
                return;
            }
        }
        int temp2=INSERTIMAGEDATA;
        if (self.uploadType==temp2) {
            
            NSLog(@"%@",data);
            return;
        }
        [self.resultData removeAllObjects];
        id  resultDict= [[[[[[[result  objectForKey:@"soap:Envelope"] objectForKey:@"soap:Body"] objectForKey:@"GetDataSetSqlResponse"] objectForKey:@"GetDataSetSqlResult"] objectForKey:@"diffgr:diffgram"] objectForKey:@"NewDataSet"] objectForKey:@"Table"];
        if ([[resultDict JSONRepresentation] hasPrefix:@"{"]) {
            [self.resultData  addObject:resultDict];
        }else{
            self.resultData=[NSMutableArray  arrayWithArray:resultDict];
            
        }
    }@catch (NSException *exception) {
        NSLog(@"master主页加载数据:%@",[exception description]);
    }
    
    [self._tableView  reloadData];
}
-(void)errorCallback{
    AppDelegate *appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    [ MBProgressHUD  hideHUDForView:appdelegate.tabbar.view animated:NO];
    NSString* okTitle = @"提醒";
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:nil message:@"网路异常" delegate:nil cancelButtonTitle:okTitle otherButtonTitles:nil];
    [alert show];
    [alert release];
}

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.resultData  count];
}
- (CGFloat)tableView:(UITableView *)_tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 95.0f;
}

// Customize the appearance of table view cells.
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"masterTableCell";
    
    photolistCell *cell = (photolistCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[photolistCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSDictionary *temp=[self.resultData objectAtIndex:indexPath.row];
    cell.orderId.text=[[temp objectForKey:@"FLIB_ID"] objectForKey:@"text"];
    NSArray *dataArray=[[[temp objectForKey:@"FLIB_CREAT_TIME"] objectForKey:@"text"] componentsSeparatedByString:@"+"];
    if (dataArray.count>0) {
        cell.updateDate.text=[[dataArray objectAtIndex:0] stringByReplacingOccurrencesOfString:@"T" withString:@" "];
    }
    cell.flid_remark.text=[[temp objectForKey:@"FLIB_REMARK"] objectForKey:@"text"];
     cell.flid_name.text=[[temp objectForKey:@"FLIB_NAME"] objectForKey:@"text"];
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *temp=[self.resultData objectAtIndex:indexPath.row];
    NSString *imagePath=[[temp objectForKey:@"FLIB_DESCRIPTION"] objectForKey:@"text"];
    NSString *url=[[[NSUserDefaults standardUserDefaults] objectForKey:@"kServiceURL"] stringByAppendingPathComponent: [imagePath stringByReplacingOccurrencesOfString:@"\\" withString:@"/"]];
    PhotoDetailViewController *pdv=[[PhotoDetailViewController alloc] initWithNibName:nil bundle:nil];
    [pdv loadImageFromURL:url andFile_id:[[temp objectForKey:@"FLIB_ID"] objectForKey:@"text"]];
    pdv.file_name=[[temp objectForKey:@"FLIB_NAME"] objectForKey:@"text"];
    [self.navigationController pushViewController:pdv animated:YES];
    [pdv release];
   
}


/*
 -(void)loginSuccess
 {   AppDelegate *appDelegate=[UIApplication sharedApplication].delegate;
 [appDelegate.tabbar dismissModalViewControllerAnimated:YES];
 [loginController release];
 loginController = nil;
 }*/


- (UIButton*) customButtom:(NSUInteger)numberOfTag withFrame:(CGRect)frame action:(SEL)action normalImage:(NSString*)normalImage lightedImage:(NSString*)lightedImage  title:(NSString *)title{
    UIButton* button;
    if (title==nil||[@"" isEqualToString:title]) {
        button = [UIButton buttonWithType:UIButtonTypeCustom];
    }else {
        button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button setTitle:title forState:UIControlStateNormal];
    }
    
    button.frame = frame;
    button.tag=numberOfTag;
    button.backgroundColor=[UIColor clearColor];
    
    if (![normalImage isEqualToString:@""]) {
        UIImage *normal_Image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:normalImage ofType:nil]];
        [button setImage:normal_Image forState:UIControlStateNormal];
    }
    
    if (![lightedImage isEqualToString:@""]) {
        UIImage *lighted_Image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:lightedImage ofType:nil]];
        [button setImage:lighted_Image forState:UIControlStateHighlighted];
        [button setImage:lighted_Image forState:UIControlStateSelected];
    }
    
    button.adjustsImageWhenHighlighted = NO;
    [button addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    return button;
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [self.locmanager stopUpdatingLocation];
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    [userdefault setObject:@"" forKey:@"gpsAddress"];
    [userdefault setObject:@"" forKey:@"gps"];
    [userdefault synchronize];
    UIAlertView *resAlertView = [[UIAlertView alloc] initWithTitle: nil
                                                           message: @"GPS解析失敗"
                                                          delegate: nil
                                                 cancelButtonTitle:@"確定"
                                                 otherButtonTitles:  nil
                                 ];
    [resAlertView show];
    [resAlertView release];
    
    // if ([error code] != kCLErrorLocationUnknown) {
    self.locmanager.delegate = nil;
    // }
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    CLLocationCoordinate2D loc = [newLocation coordinate];
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    [userdefault setObject:[NSString stringWithFormat:@"%f,%f",loc.latitude,loc.longitude] forKey:@"gps"];
    [userdefault synchronize];
    MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:loc];
    
    geocoder.delegate = self;
    
    [geocoder start];
    [geocoder release];
    self.locmanager.delegate = nil;
}
- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark {
    NSDictionary* place=placemark.addressDictionary;
    NSArray *address=[place objectForKey:@"FormattedAddressLines"];
    NSString *addressDetail=@"";
    if (address.count>0) {
        addressDetail=[address objectAtIndex:0];
    }
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    [userdefault setObject:addressDetail forKey:@"gpsAddress"];
    [userdefault synchronize];

}

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error{
    NSUserDefaults *userdefault=[NSUserDefaults standardUserDefaults];
    [userdefault setObject:@"" forKey:@"gpsAddress"];
    [userdefault synchronize];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation==UIDeviceOrientationPortrait);
}
- (BOOL)shouldAutorotate{
    return NO;
}
- (NSUInteger)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAllButUpsideDown;
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc{
    //[loginController release];
    [_locmanager release];
    [_pickerController release];
    [requestManager  release];
    [_tableView  release];
    [resultData  release];
    [super dealloc];
}



@end
